package com.android.pantryshopping.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.android.pantryshopping.R;
import com.android.pantryshopping.bean.Commodity;
import com.android.pantryshopping.util.BitMapTool;

import java.util.ArrayList;
import java.util.List;

public class CommodityAdapter extends RecyclerView.Adapter<CommodityAdapter.ViewHolder> {

    private Context mContext;
    private List<Commodity> mCommodities;

    private onCommodityItemListener mListener;

    public CommodityAdapter(Context context) {
        mContext = context;
        mCommodities = new ArrayList<>();
    }

    public void setCommodities(ArrayList<Commodity> commodityList) {
        mCommodities = commodityList;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_commodity,parent,false);
        ViewHolder holder = new ViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Commodity commodity = mCommodities.get(position);
        Bitmap bitmap = BitmapFactory.decodeFile(commodity.getImage());
        holder.mImageView.setImageBitmap(bitmap);
        holder.mTvId.setText(commodity.getId());
        holder.mTvName.setText(commodity.getName());
        holder.mTvPrice.setText(commodity.getPrice());
        holder.mTvNum.setText(commodity.getQuantity());

        holder.itemView.setOnClickListener(v -> {
            mListener.onCommodityClick(position);
        });
    }

    @Override
    public int getItemCount() {
        return mCommodities.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        private ImageView mImageView;
        private TextView mTvId;
        private TextView mTvName;
        private TextView mTvPrice;
        private TextView mTvNum;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            mImageView = itemView.findViewById(R.id.img_sp);
            mTvId = itemView.findViewById(R.id.tv_id);
            mTvName = itemView.findViewById(R.id.tv_name);
            mTvPrice = itemView.findViewById(R.id.tv_price);
            mTvNum = itemView.findViewById(R.id.tv_num);
        }
    }

    public interface onCommodityItemListener{
        void onCommodityClick(int position);
    }

    public void setOnCommodityItemListener(onCommodityItemListener listener) {
        mListener = listener;
    }
}
